package org.luckystrophe.snowtoms;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.fragment.INFOFragment_;
import org.luckystrophe.snowtoms.fragment.RankFragment;
import org.luckystrophe.snowtoms.fragment.RankFragment_;
import org.luckystrophe.snowtoms.fragment.SNSFragment_;
import org.luckystrophe.snowtoms.listener.SnowTomsTabListener;
import org.luckystrophe.snowtoms.manager.SnowtomsUtils;
import org.luckystrophe.snowtoms.model.CoachMarks;
import org.luckystrophe.snowtoms.model.JsonRequest;
import org.luckystrophe.snowtoms.model.impl.CoachMarksImpl;
import org.luckystrophe.snowtoms.model.impl.LoginPost;
import org.luckystrophe.snowtoms.model.impl.PostActivityIntent;
import org.luckystrophe.snowtoms.pref.AppPreference_;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.androidquery.util.AQUtility;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EActivity
public class MainActivity extends SherlockFragmentActivity {

	@Pref
	UserPreference_ pref;

	@Pref
	AppPreference_ appPref;

	@Bean
	SnowtomsUtils utils;

	@Bean(LoginPost.class)
	JsonRequest loginPost;

	@Bean(CoachMarksImpl.class)
	CoachMarks coachMarks;

	static final private int POST_ACITIVTY_RESULT_CODE = 0;
	static final private int SETTING_ACTIVITY_RESULT_CODE = 1;
	static final public int REPLY_ACTIVITY_RESULT_CODE = 2;

	@Override
	public void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);

		final ActionBar actionBar = getSupportActionBar();

		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.addTab(actionBar.newTab().setIcon(R.drawable.tab_icon_rank).setTag("RANK")
				.setTabListener(new SnowTomsTabListener<RankFragment_>(this, "Rank", RankFragment_.class)));
		actionBar.addTab(actionBar.newTab().setIcon(R.drawable.tab_icon_sns).setTag("SNS")
				.setTabListener(new SnowTomsTabListener<SNSFragment_>(this, "SNS", SNSFragment_.class)));
		actionBar.addTab(actionBar.newTab().setIcon(R.drawable.tab_icon_location).setTag("INFO")
				.setTabListener(new SnowTomsTabListener<INFOFragment_>(this, "INFO", INFOFragment_.class)));

		// actionBar.hide();
		//
		// FragmentManager fragmentManager = getSupportFragmentManager();
		// FragmentTransaction fragmentTransaction =
		// fragmentManager.beginTransaction();
		//
		// fragmentTransaction.replace(android.R.id.content, fragment1);
		// fragmentTransaction.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 10, Menu.NONE, "Settings").setIcon(R.drawable.btn_system)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		SubMenu subMenu = menu.addSubMenu("Writings");
		subMenu.add(1, 20, Menu.NONE, "PostWithPhoto").setIcon(R.drawable.upload_camera)
				.setTitle(R.string.auth_message);
		subMenu.add(1, 30, Menu.NONE, "PostWithText").setIcon(R.drawable.upload_writing)
				.setTitle(R.string.ordinary_message);
		// 임시 폐쇄
		// subMenu.add(1, 40, Menu.NONE,
		// "Report").setIcon(R.drawable.upload_report).setTitle(R.string.report_message);

		MenuItem subMenuItem = subMenu.getItem();
		subMenuItem.setIcon(R.drawable.btn_upload).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		menu.add(2, 50, Menu.NONE, "Settings");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case 10:
			moveSettingActivity();
			break;

		case 20:
			movePostActivity(new PostActivityIntent(true, true, true, 1));
			break;

		case 30:
			movePostActivity(new PostActivityIntent(false, false, false, 0));
			break;

		// case 40:
		// movePostActivity(new PostActivityIntent(false, false, false, 2));
		// break;

		case 50:
			moveSettingActivity();
			break;

		default:
			break;
		}
		return true;
	}

	public void closeFacebookSession() {
		Session.getActiveSession().closeAndClearTokenInformation();
	}

	public void movePostActivity(PostActivityIntent postActivityIntent) {
		Session session = Session.getActiveSession();

		final Intent postActivity = new Intent(this, PostActivity_.class);
		postActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		postActivity.putExtra(PostActivity.POST_OPTION, postActivityIntent);

		if (session != null && session.isOpened() && !session.isClosed()) {
			openPostActivity(postActivity);

		} else {
			Session.openActiveSession(this, true, new StatusCallback() {
				@Override
				public void call(Session session, SessionState state, Exception exception) {
					if (session.isOpened()) {
						Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
							@Override
							public void onCompleted(GraphUser user, Response response) {
								if (user != null) {
									pref.collaboId().put(user.getId());
									pref.loginType().put("fb");
									pref.name().put(user.getName());
									getConnection(postActivity);
								}
							}
						});
						Request.executeBatchAsync(request);
					}
				}
			});
		}
	}

	public void moveSettingActivity() {
		Intent i = new Intent(this, SettingActivity_.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
		overridePendingTransition(R.anim.rightin, R.anim.leftout);
		startActivityForResult(i, SETTING_ACTIVITY_RESULT_CODE);
	}

	public void openPostActivity(Intent postActivity) {
		if (pref.location().get() == null) {
			utils.setLocationDialog(this, false, null, null);
		} else {
			startActivityForResult(postActivity, POST_ACITIVTY_RESULT_CODE);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishActivity();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void finishActivity() {
		finish();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == POST_ACITIVTY_RESULT_CODE) {
			if (resultCode != RESULT_CANCELED) {
				getSupportActionBar().setSelectedNavigationItem(1);
				updateSNS();
				int messageType = data.getIntExtra("messageType", 0);
				if (messageType == PostActivityIntent.AUTH_MESSAGE) {
					showSnowContestDialog();
				}
			}
		} else if (requestCode == SETTING_ACTIVITY_RESULT_CODE) {
			if (resultCode != RESULT_CANCELED) {
				getSupportActionBar().setSelectedNavigationItem(0);
				updateSNS();
			}
			return;
		} else if (requestCode == REPLY_ACTIVITY_RESULT_CODE) {
			if (resultCode != RESULT_CANCELED) {
				updateSNS();
			}
			return;
		}
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		super.onWindowFocusChanged(hasWindowFocus);
		RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl_mainSize);
		TextView tv = (TextView) findViewById(R.id.tv_districtrank);
		if (rl != null) {
			RankFragment.TICK_HEIGHT = (rl.getHeight() - tv.getHeight()) / 25;
			RankFragment.TICK_COUNT = (rl.getHeight() - tv.getHeight()) / 35;
		}
	}

	@Background
	public void getConnection(Intent postActivity) {
		try {
			afterGetConnection(loginPost.sendJsonRequest(), postActivity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@UiThread
	public void afterGetConnection(JSONObject jo, Intent postActivity) {
		((LoginPost) loginPost).getAuthcode(jo);
		openPostActivity(postActivity);
		updateSNS();
	}

	public void updateSNS() {
		SNSFragment_ snsFlagment = (SNSFragment_) getSupportFragmentManager().findFragmentByTag("SNS");
		if (snsFlagment != null) {
			snsFlagment.getLists();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		AQUtility.cleanCacheAsync(this);
	}

	@UiThread
	public void showSnowContestDialog() {
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		LayoutInflater adbInflater = LayoutInflater.from(this);
		View eulaLayout = adbInflater.inflate(R.layout.dialog_snowcontest, null);
		final CheckBox dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.skip);
		adb.setView(eulaLayout);
		adb.setTitle("공모전 참여");
		adb.setMessage(Html.fromHtml("\"서울시 눈치우기 인증샷 공모\"에도 참여하시겠습니까? <br>" + "(일정조건 충족시 3만원 상당 문화상품권 지급)"));
		adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				long checkboxResult = 0L;
				if (dontShowAgain.isChecked())
					checkboxResult = System.currentTimeMillis();
				appPref.skipMessage().put(checkboxResult);
				startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse("http://wow.seoul.go.kr/event/13471210hope/write.jsp")));
				return;
			}
		});

		adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				long checkboxResult = 0L;
				if (dontShowAgain.isChecked())
					checkboxResult = System.currentTimeMillis();
				appPref.skipMessage().put(checkboxResult);
				return;
			}
		});

		long skipMessage = appPref.skipMessage().get();

		if (skipMessage == 0L) {
			adb.show();
		} else if (isOver3Days(skipMessage)) {
			adb.show();
		}
	}

	public boolean isOver3Days(long savedTime) {
		long now = System.currentTimeMillis();
		long gap = now - savedTime;
		long threeDays = 3 * 24 * 60 * 60 * 1000; // 1시간 60 * 60 * 1000
		return gap > threeDays;
	}

}
